package com.controller;

import com.github.qcloudsms.SmsSingleSender;
import com.github.qcloudsms.SmsSingleSenderResult;
import com.pojo.Result;
import com.pojo.Sms;
import org.json.JSONException;
import org.springframework.web.bind.annotation.*;

import javax.xml.ws.http.HTTPException;
import java.io.IOException;

//发短信
//跨域
@CrossOrigin
@RestController
@RequestMapping("/sms")
public class SmsController {
    @PostMapping
    public Result sms(@RequestBody Sms sms){
        int appid = 1400769812;
        String appkey = "8b0f81c1e86b5fc78832d4979124fbd1";
        int templateId = 1621948;
        String smsSign ="tom8个8个人公众号";
        try {
            //设置随机验证码
            String x= String.valueOf((int)((Math.random()*9+1)* Math.pow(10,6-1)));
            //System.out.println(x);
            sms.setCode(x);
            //传参数
            String[] params = {sms.getCode()};
            SmsSingleSender sender = new SmsSingleSender(appid,appkey);
            SmsSingleSenderResult result = sender.sendWithParam("86",sms.getPhoneNumber(),templateId,params,smsSign,"","");

            Result result1 = new Result();
            result1.setCode(200);
            result1.setMsg("发送成功");
            result1.setData(sms.getCode());
            return result1;
        }catch (JSONException e) {
            e.printStackTrace();
        }catch (IOException e) {
            e.printStackTrace();
        } catch (com.github.qcloudsms.httpclient.HTTPException e) {
            e.printStackTrace();
        }
        return new Result(500,"发送失败",null);
    }
}